import { createReducer, createAsyncAction } from 'redux-action-tools';
import axios from 'axios'
const appInstance = axios.create({
  baseURL: 'http://localhost:5000/',
  timeout: 1000,
  headers: {
    'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjU3ZmNhODc3NTIxNDA1MjM5NDJjNmU0NSIsImlhdCI6MTQ4MTg1NDE4Mn0.oP_2Vd2C22aEN6Xp0qI5Hs92HXsNasPCuKPlr4ZAKhQ',
     "accept": "application/json"
  }
});
// ------------------------------------
// 这里为所有跟答题期数有关热reducer
// ------------------------------------


const GETALLFIELDS = 'GETALLFIELDS',
      ADDONEFIELD='ADDONEFIELD',
      DELETEONEFIELD = 'DELETEONEFIELD';

export const getAllFields = createAsyncAction(GETALLFIELDS, () => {

  return appInstance.get(`/fields`).then(response=>Promise.resolve(response.data))

})
const GETALLFIELDS_SUCCESS = (state, action) => {
  // console.log(state,action);
  return Object.assign({}, state, { fieldList: action.payload.data})
}



export const deleteOneFieldById = createAsyncAction(DELETEONEFIELD, (termId) => {
  console.log(termId);
  return appInstance.delete(`/fields/${termId}`).then(response=>Promise.resolve(response.data))

})
const DELETEONEFIELD_SUCCESS = (state, action) => {
  console.log("请求成功了",action);

  let fieldList=state.fieldList.filter(term=>{
    return term._id!==action.payload.data._id;
  });
   return Object.assign({}, state, { fieldList:fieldList,fieldsLoading:false })
}


export const addOneField = createAsyncAction(ADDONEFIELD, (term) => {
  console.log(term)
   return appInstance.post(`/fields/`,{term:term}).then(response=>Promise.resolve(response.data))

})
const ADDONEFIELD_SUCCESS = (state, action) => {
  // console.log("请求成功了",action,action.payload.data.fields);

  return Object.assign({}, state, { fieldList:[  action.payload.data,...state.fieldList],fieldsLoading:false })
}



const getError = (state, action) => {
  console.log("请求失败了");
  return state
}

const fieldListReducer = createReducer()
  .when(GETALLFIELDS)
  .done(GETALLFIELDS_SUCCESS)
  .when(ADDONEFIELD)
  .done(ADDONEFIELD_SUCCESS)
  .when(DELETEONEFIELD)
  .done(DELETEONEFIELD_SUCCESS)
  .failed(getError)
  .build({ fieldList: [],fieldLoading:false });

export default fieldListReducer


